package com.john.app.bmical;

import java.text.DecimalFormat;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 主页
 * @author wenyong
 *
 */
public class MainActivity extends FragmentActivity {
	public static final String PREF = "BMI_PREF";
	public static final String PREF_HEIGHT = "BMI_PREF_HEIGHT";
	public static final String BMI_RESULT_FLAG = "BMI_RESULT";

	protected static final int MENU_ABOUT = Menu.FIRST;
	protected static final int MENU_QUIT = Menu.FIRST + 1;

	private static final int BMI_HIGH = 1;
	private static final int BMI_LOW = -1;
	
	private static int BMI_RESULT = 0;

//	private Button btnSuggest;
	private Button btnCal;
	private EditText etxtHeight;
	private EditText etxtWeight;
	private TextView txtResult;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		findViews();
		restorePrefs();
		setListener();

//		btnSuggest.setVisibility(View.GONE);
		// Keep the Screen On
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		// Clear the Flags of Keep the Screen On
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		// In AndroidManifest.xml must set up WAKE_LOCK permission to Keep Screen On 
		//<uses-permission android:name="android.permission.WAKE_LOCK" />
		
	}

	@Override
	protected void onStop() {
		super.onStop();
		
		// 因为身高不常变化，所以记录身高值
		String heightStr = etxtHeight.getText().toString();
		if (!TextUtils.isEmpty(heightStr)) {
			// Save use preference. Use Editor object to make change
			SharedPreferences settings = getSharedPreferences(PREF, 0);
			settings.edit().putString(PREF_HEIGHT, heightStr).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		menu.add(0, MENU_ABOUT, 0, "关于……");
		menu.add(0, MENU_QUIT, 0, "退出");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case MENU_ABOUT:
			showAboutPage();
		case MENU_QUIT:
			finish();
		}
		return true;
	}

	/**
	 * 查找Views
	 */
	private void findViews() {
		txtResult = (TextView) findViewById(R.id.txtResult);
		etxtHeight = (EditText) findViewById(R.id.etxtHeight);
		etxtWeight = (EditText) findViewById(R.id.etxtWeight);
//		btnSuggest = (Button) findViewById(R.id.btnSuggest);
		btnCal = (Button) findViewById(R.id.btnCal);
	}

	/**
	 * 绑定Listener
	 */
	private void setListener() {
		btnCal.setOnClickListener(btnCalOnClickListener);
//		btnSuggest.setOnClickListener(btnSuggestOnClickListener);
	}

	// btnCalOnClickListener
	private OnClickListener btnCalOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View arg) {

			// check input
			if (checkInput() == false) {
				return;
			}

			closeInputMethod();
			
			DecimalFormat fomat = new DecimalFormat("0.00");
			double height = Double.valueOf(etxtHeight.getText().toString()) / 100;
			double weight = Double.valueOf(etxtWeight.getText().toString());
			double bmi = weight / (height * height);

			txtResult.setText("你的BMI值是：" + fomat.format(bmi));

			// show result description
			if (bmi > 25) {
				txtResult.setText(R.string.advice_heavy);
//				btnSuggest.setVisibility(View.VISIBLE);
				// txtResult.setBackgroundColor(R.drawable.myrect);
				txtResult.setBackgroundColor(getResources().getColor(
						R.color.red));
				BMI_RESULT = BMI_HIGH;
			} else if (bmi < 20) {
				txtResult.setText(R.string.advice_light);
//				btnSuggest.setVisibility(View.VISIBLE);
				txtResult.setBackgroundColor(getResources().getColor(
						R.color.blue));
				BMI_RESULT = BMI_LOW;
			} else {
				txtResult.setText(R.string.advice_average);
				txtResult.setBackgroundColor(getResources().getColor(
						R.color.green));
				BMI_RESULT = 0;
//				btnSuggest.setVisibility(View.GONE);
			}
			
			// init SuggestFragment
			if(findViewById(R.id.suggest_fragment_container) != null) {
				
	            // Create an instance of ExampleFragment
				SuggestFragment sFragment = new SuggestFragment();
				
	            // In case this activity was started with special instructions from an Intent,
	            // pass the Intent's extras to the fragment as arguments				
				sFragment.setArguments(getIntent().getExtras());
				
				Bundle bundle = new Bundle();
				bundle.putInt(BMI_RESULT_FLAG, BMI_RESULT);
				sFragment.setArguments(bundle);
				
				// Add the fragment to the 'fragment_container' FrameLayout
	            getSupportFragmentManager().beginTransaction()
	                    .add(R.id.suggest_fragment_container, sFragment).commit();
			}
						
		}

	};

	/**
	 * 检查输入
	 */
	private boolean checkInput() {
		String weightVar = etxtWeight.getText().toString();
		String heightVar = etxtHeight.getText().toString();
		if (weightVar == null || weightVar.trim().equals("")) {
			etxtWeight.setError("请输入内容！");
			return false;
		}
		if (heightVar == null || heightVar.trim().equals("")) {
			etxtHeight.setError("请输入内容！");
			return false;
		}
		return true;
	}

	/**
	 * 弹出《关于》页面
	 */
	private void showAboutPage() {
		Uri uri = Uri.parse(getString(R.string.homepage_uri));
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent);
	}

	/**
	 * 从记录中取值
	 */
	private void restorePrefs() {
		SharedPreferences settings = getSharedPreferences(PREF, 0);
		String prefHeight = settings.getString(PREF_HEIGHT, "");
		if (!TextUtils.isEmpty(prefHeight)) {
			// 填入记录的值
			etxtHeight.setText(prefHeight);
			// 转移焦点
			etxtWeight.requestFocus();
		}
	}
	
	/**
	 * 关闭输入法
	 */
	private void closeInputMethod() {
	    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	    boolean isOpen = imm.isActive();
	    if (isOpen) {
	        // imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//没有显示则显示
	        imm.hideSoftInputFromWindow(etxtHeight.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	    }
	}

}
